<template>
  <div class="project-detail-container">
    <div class="top-bar">
      <div class="top-left">
        <img src="../assets/logo.png" alt="系统Logo" class="logo" />
        <span class="title">皮革产品打样需求管理系统</span>
      </div>

      <div class="detail-title">
        <span v-if="project">{{ project.projectName }} - {{ isEditMode ? '编辑需求' : '需求详情' }}</span>
        <span v-else>加载中...</span>
      </div>

      <div class="buttons">
        <button class="primary-button" @click="goBack">
          <i class="iconfont icon-back"></i> 返回列表
        </button>

        <template v-if="isProjectOwner">
          <button v-if="!isEditMode" class="primary-button edit-button" @click="enterEditMode">
            <i class="iconfont icon-edit"></i> 修改
          </button>
          <button v-else class="primary-button save-button" @click="saveChanges">
            <i class="iconfont icon-save"></i> 保存
          </button>
          <button v-if="isEditMode" class="primary-button cancel-button" @click="cancelEdit">
            <i class="iconfont icon-close"></i> 取消
          </button>
        </template>

        <button class="primary-button download-button" @click="printPDF">
          <i class="iconfont icon-download"></i> 下载为PDF
        </button>
      </div>
    </div>

    <div class="main-content">
      <el-card class="project-info-card">
        <template #header>
          <div class="card-header">
            <h2>项目基本信息</h2>
            <el-tag v-if="project" :type="getStatusType(project.status)">
              {{ getStatusText(project.status) }}
            </el-tag>
            <el-tag v-else>加载中...</el-tag>
          </div>
        </template>
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>
        <div v-else-if="project" class="project-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">项目名称：</span>
              <span class="value">{{ project.projectName }}</span>
            </div>
            <div class="info-item">
              <span class="label">项目编号：</span>
              <span class="value">{{ project.projectCode }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">客户名称：</span>
              <span class="value">{{ project.clientName }}</span>
            </div>
            <div class="info-item">
              <span class="label">客户联系人：</span>
              <span class="value">{{ project.clientContact }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ project.clientPhone }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDate(project.createTime) }}</span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item">
              <span class="label">项目状态：</span>
              <span class="value">
                <el-tag :type="getStatusType(project.status)">{{ getStatusText(project.status) }}</el-tag>
              </span>
            </div>
          </div>
          <div class="info-row">
            <div class="info-item full-width">
              <span class="label">项目目标：</span>
              <span class="value">{{ project.projectGoal }}</span>
            </div>
          </div>
        </div>
        <div v-else class="error-message">
          <el-empty description="未找到项目信息" />
        </div>
      </el-card>

      <el-card class="requirement-detail-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <h2>需求详情</h2>
          </div>
        </template>
        <div class="require">
          <el-tabs v-model="activeRequirementId">
            <el-tab-pane
                v-for="req in requirements"
                :key="req.id"
                :label="'需求 ' + req.id"
                :name="String(req.id)"
            >
              <div v-if="loading" class="loading-container">
                <el-skeleton :rows="10" animated />
              </div>
              <div v-else-if="requirements && requirements.length > 0" class="requirement-tabs">
                <el-tabs v-model="activeTab">
                  <el-tab-pane label="产品设计细节" name="design">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">文件名称：</span>
                          <span v-if="!isEditMode" class="value">{{ req.fileName }}</span>
                          <el-input v-else v-model="req.fileName" size="small" />
                        </div>
                        <div class="info-item">
                          <span class="label">版本：</span>
                          <span v-if="!isEditMode" class="value">{{ req.version }}</span>
                          <el-input v-else v-model="req.version" size="small" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">产品形状：</span>
                          <span v-if="!isEditMode" class="value">{{ getProductShapeText(req.productShape) }}</span>
                          <el-select v-else v-model="req.productShape" size="small">
                            <el-option v-for="shape in productShapes" :key="shape.value" :label="shape.label" :value="shape.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">产品结构：</span>
                          <span v-if="!isEditMode" class="value">{{ getProductStructureText(req.productStructure) }}</span>
                          <el-select v-else v-model="req.productStructure" size="small">
                            <el-option v-for="structure in productStructures" :key="structure.value" :label="structure.label" :value="structure.value" />
                          </el-select>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">闭合类型：</span>
                          <span v-if="!isEditMode" class="value">{{ getClosureTypeText(req.closureType) }}</span>
                          <el-select v-else v-model="req.closureType" size="small">
                            <el-option v-for="type in closureTypes" :key="type.value" :label="type.label" :value="type.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">装饰：</span>
                          <span v-if="!isEditMode" class="value">{{ req.decoration || '无' }}</span>
                          <el-input v-else v-model="req.decoration" size="small" placeholder="无" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">口袋类型：</span>
                          <span v-if="!isEditMode" class="value">{{ getPocketTypeText(req.pocketType) }}</span>
                          <el-select v-else v-model="req.pocketType" size="small">
                            <el-option v-for="type in pocketTypes" :key="type.value" :label="type.label" :value="type.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">尺寸：</span>
                          <span v-if="!isEditMode" class="value">{{ req.dimensions }}</span>
                          <el-input v-else v-model="req.dimensions" size="small" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">颜色代码：</span>
                          <span v-if="!isEditMode" class="value">{{ req.colorCode }}</span>
                          <el-input v-else v-model="req.colorCode" size="small" />
                        </div>
                        <div class="info-item">
                          <span class="label">颜色色调：</span>
                          <span v-if="!isEditMode" class="value">{{ getColorShadeText(req.colorShade) }}</span>
                          <el-select v-else v-model="req.colorShade" size="small">
                            <el-option v-for="shade in colorShades" :key="shade.value" :label="shade.label" :value="shade.value" />
                          </el-select>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">图案类型：</span>
                          <span v-if="!isEditMode" class="value">{{ getPatternTypeText(req.patternType) }}</span>
                          <el-select v-else v-model="req.patternType" size="small">
                            <el-option v-for="type in patternTypes" :key="type.value" :label="type.label" :value="type.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">图案位置：</span>
                          <span v-if="!isEditMode" class="value">{{ req.patternLocation || '无' }}</span>
                          <el-input v-else v-model="req.patternLocation" size="small" placeholder="无" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">图案尺寸：</span>
                          <span v-if="!isEditMode" class="value">{{ req.patternSize || '无' }}</span>
                          <el-input v-else v-model="req.patternSize" size="small" placeholder="无" />
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="材质偏好" name="material">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">皮革类型：</span>
                          <span v-if="!isEditMode" class="value">{{ getLeatherTypeText(req.leatherType) }}</span>
                          <el-select v-else v-model="req.leatherType" size="small">
                            <el-option v-for="type in leatherTypes" :key="type.value" :label="type.label" :value="type.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">皮革厚度：</span>
                          <span v-if="!isEditMode" class="value">{{ req.leatherThickness }}</span>
                          <el-input v-else v-model="req.leatherThickness" size="small" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">皮革表面处理：</span>
                          <span v-if="!isEditMode" class="value">{{ getLeatherFinishText(req.leatherFinish) }}</span>
                          <el-select v-else v-model="req.leatherFinish" size="small">
                            <el-option v-for="finish in leatherFinishes" :key="finish.value" :label="finish.label" :value="finish.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">内衬类型：</span>
                          <span v-if="!isEditMode" class="value">{{ getLiningTypeText(req.liningType) }}</span>
                          <el-select v-else v-model="req.liningType" size="small">
                            <el-option v-for="type in liningTypes" :key="type.value" :label="type.label" :value="type.value" />
                          </el-select>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">内衬颜色：</span>
                          <span v-if="!isEditMode" class="value">{{ req.liningColor || '无' }}</span>
                          <el-input v-else v-model="req.liningColor" size="small" placeholder="无" />
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="预期效果" name="effect">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">柔软度：</span>
                          <span v-if="!isEditMode" class="value">{{ getSoftnessText(req.softness) }}</span>
                          <el-select v-else v-model="req.softness" size="small">
                            <el-option v-for="softness in softnessOptions" :key="softness.value" :label="softness.label" :value="softness.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">耐用性：</span>
                          <span v-if="!isEditMode" class="value">{{ getDurabilityText(req.durability) }}</span>
                          <el-select v-else v-model="req.durability" size="small">
                            <el-option v-for="durability in durabilityOptions" :key="durability.value" :label="durability.label" :value="durability.value" />
                          </el-select>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">防水性：</span>
                          <span v-if="!isEditMode" class="value">{{ getWaterResistanceText(req.waterResistance) }}</span>
                          <el-select v-else v-model="req.waterResistance" size="small">
                            <el-option v-for="resistance in waterResistanceOptions" :key="resistance.value" :label="resistance.label" :value="resistance.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">光泽度：</span>
                          <span v-if="!isEditMode" class="value">{{ getShineText(req.shine) }}</span>
                          <el-select v-else v-model="req.shine" size="small">
                            <el-option v-for="shine in shineOptions" :key="shine.value" :label="shine.label" :value="shine.value" />
                          </el-select>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="工艺要求" name="process">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">切割精度：</span>
                          <span v-if="!isEditMode" class="value">{{ getCuttingAccuracyText(req.cuttingAccuracy) }}</span>
                          <el-select v-else v-model="req.cuttingAccuracy" size="small">
                            <el-option v-for="accuracy in cuttingAccuracyOptions" :key="accuracy.value" :label="accuracy.label" :value="accuracy.value" />
                          </el-select>
                        </div>
                        <div class="info-item">
                          <span class="label">缝纫密度：</span>
                          <span v-if="!isEditMode" class="value">{{ getSewingDensityText(req.sewingDensity) }}</span>
                          <el-select v-else v-model="req.sewingDensity" size="small">
                            <el-option v-for="density in sewingDensityOptions" :key="density.value" :label="density.label" :value="density.value" />
                          </el-select>
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item full-width">
                          <span class="label">组装顺序：</span>
                          <span v-if="!isEditMode" class="value">{{ req.assemblyOrder || '无特殊要求' }}</span>
                          <el-input v-else v-model="req.assemblyOrder" type="textarea" :rows="2" placeholder="无特殊要求" />
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="成本要求" name="cost">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">材料成本：</span>
                          <span v-if="!isEditMode" class="value">{{ req.materialCost || '未指定' }}</span>
                          <el-input v-else v-model="req.materialCost" size="small" placeholder="未指定" />
                        </div>
                        <div class="info-item">
                          <span class="label">加工成本：</span>
                          <span v-if="!isEditMode" class="value">{{ req.processingCost || '未指定' }}</span>
                          <el-input v-else v-model="req.processingCost" size="small" placeholder="未指定" />
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="生产可行性" name="feasibility">
                    <div class="tab-content">
                      <div class="info-row">
                        <div class="info-item">
                          <span class="label">工艺可行性：</span>
                          <span v-if="!isEditMode" class="value">{{ req.processFeasibility || '未评估' }}</span>
                          <el-input v-else v-model="req.processFeasibility" size="small" placeholder="未评估" />
                        </div>
                        <div class="info-item">
                          <span class="label">生产周期：</span>
                          <span v-if="!isEditMode" class="value">{{ req.productionTime || '未评估' }}</span>
                          <el-input v-else v-model="req.productionTime" size="small" placeholder="未评估" />
                        </div>
                      </div>
                      <div class="info-row">
                        <div class="info-item full-width">
                          <span class="label">备注：</span>
                          <span v-if="!isEditMode" class="value">{{ req.notes || '无' }}</span>
                          <el-input v-else v-model="req.notes" type="textarea" :rows="2" placeholder="无" />
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
              <div v-else class="error-message">
                <el-empty description="未找到需求详情信息" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElLoading, ElNotification } from 'element-plus';
import { useStore } from 'vuex';

const route = useRoute();
const router = useRouter();
const store = useStore();
const projectId = ref(route.params.id);
const project = ref(null);
const requirements = ref([]);
const activeRequirementId = ref('');
const activeTab = ref('design');
const loading = ref(true);
const isEditMode = ref(false);
const originalRequirements = ref([]);

const productShapes = [
  { value: 'SQUARE', label: '方形' },
  { value: 'RECTANGLE', label: '矩形' },
  { value: 'STREAMLINE', label: '流线型' },
  { value: 'CIRCLE', label: '圆形' },
  { value: 'IRREGULAR', label: '不规则' }
];

const productStructures = [
  { value: 'SINGLE_LAYER', label: '单层' },
  { value: 'MULTI_LAYER', label: '多层' },
  { value: 'WITH_POCKETS', label: '带口袋' },
  { value: 'FOLDABLE', label: '可折叠' }
];

const closureTypes = [
  { value: 'ZIPPER', label: '拉链' },
  { value: 'BUTTON', label: '按钮' },
  { value: 'MAGNETIC', label: '磁扣' },
  { value: 'HOOK', label: '钩扣' }
];

const pocketTypes = [
  { value: 'ZIPPERED', label: '拉链口袋' },
  { value: 'PATCH', label: '贴袋' },
  { value: 'HIDDEN', label: '隐藏口袋' }
];

const colorShades = [
  { value: 'DARK', label: '深色' },
  { value: 'LIGHT', label: '浅色' },
  { value: 'NEUTRAL', label: '中性色' }
];

const patternTypes = [
  { value: 'EMBOSSED', label: '压纹' },
  { value: 'PRINTED', label: '印花' },
  { value: 'ENGRAVED', label: '雕刻' }
];

const leatherTypes = [
  { value: 'FULL_GRAIN', label: '全粒面皮革' },
  { value: 'SUEDE', label: '绒面皮革' },
  { value: 'ARTIFICIAL', label: '人造皮革' }
];

const leatherFinishes = [
  { value: 'MATTE', label: '哑光' },
  { value: 'BRIGHT', label: '亮面' }
];

const liningTypes = [
  { value: 'POLYESTER', label: '聚酯纤维' },
  { value: 'MICROFIBER', label: '超细纤维' }
];

const softnessOptions = [
  { value: 'VERY_SOFT', label: '非常柔软' },
  { value: 'MODERATELY_SOFT', label: '适中柔软' },
  { value: 'STIFF', label: '硬挺' }
];

const durabilityOptions = [
  { value: 'HIGH', label: '高' },
  { value: 'MEDIUM', label: '中' },
  { value: 'LOW', label: '低' }
];

const waterResistanceOptions = [
  { value: 'WATERPROOF', label: '防水' },
  { value: 'SPLASH_PROOF', label: '防泼水' },
  { value: 'NOT_WATERPROOF', label: '非防水' }
];

const shineOptions = [
  { value: 'MATTE', label: '哑光' },
  { value: 'SEMI_MATTE', label: '半哑光' },
  { value: 'NATURAL', label: '自然光泽' },
  { value: 'HIGH_GLOSS', label: '高光泽' }
];

const cuttingAccuracyOptions = [
  { value: '1MM', label: '1毫米' },
  { value: '2MM', label: '2毫米' },
  { value: '3MM', label: '3毫米' }
];

const sewingDensityOptions = [
  { value: '8_9', label: '8-9针/英寸' },
  { value: '10_12', label: '10-12针/英寸' },
  { value: '12_14', label: '12-14针/英寸' }
];

const isProjectOwner = computed(() => {
  if (!project.value || !store.state.user) return false;
  return project.value.createUserId === store.state.user.id;
});

const escapeHtml = (unsafe) => {
  if (!unsafe) return '';
  return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
};

const fetchProjectInfo = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get(`/api/projects/${projectId.value}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    project.value = response.data.data;
  } catch (error) {
    ElNotification.error({ title: '错误', message: '获取项目信息失败' });
    console.error('获取项目信息失败:', error);
  }
};

const fetchRequirementDetail = async () => {
  try {
    loading.value = true;
    const token = localStorage.getItem('token');
    const response = await axios.get(`/api/requirements/project/${projectId.value}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    const responseData = response.data.data || response.data.result || response.data;
    const data = Array.isArray(responseData) ? responseData : [responseData];

    requirements.value = data.map(item => ({
      id: item.id ?? 0,
      fileName: item.fileName ?? '',
      version: item.version ?? '',
      productShape: item.productShape ?? '',
      productStructure: item.productStructure ?? '',
      closureType: item.closureType ?? '',
      decoration: item.decoration ?? '',
      pocketType: item.pocketType ?? '',
      dimensions: item.dimensions ?? '',
      colorCode: item.colorCode ?? '',
      colorShade: item.colorShade ?? '',
      patternType: item.patternType ?? '',
      patternLocation: item.patternLocation ?? '',
      patternSize: item.patternSize ?? '',
      leatherType: item.leatherType ?? '',
      leatherThickness: item.leatherThickness ?? '',
      leatherFinish: item.leatherFinish ?? '',
      liningType: item.liningType ?? '',
      liningColor: item.liningColor ?? '',
      softness: item.softness ?? '',
      durability: item.durability ?? '',
      waterResistance: item.waterResistance ?? '',
      shine: item.shine ?? '',
      cuttingAccuracy: item.cuttingAccuracy ?? '',
      sewingDensity: item.sewingDensity ?? '',
      assemblyOrder: item.assemblyOrder ?? '',
      materialCost: item.materialCost ?? '',
      processingCost: item.processingCost ?? '',
      processFeasibility: item.processFeasibility ?? '',
      productionTime: item.productionTime ?? '',
      notes: item.notes ?? '',
      ...item
    }));

    originalRequirements.value = JSON.parse(JSON.stringify(requirements.value));

    if (requirements.value.length > 0) {
      activeRequirementId.value = String(requirements.value[0].id);
    }
  } catch (error) {
    console.error('获取需求详情失败:', error);
    ElNotification.error({ title: '错误', message: '获取需求详情失败' });
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateString) => {
  if (!dateString) return '未知日期';
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

const getStatusText = (status) => {
  switch (status) {
    case 0: return '已取消';
    case 1: return '进行中';
    case 2: return '已完成';
    default: return '未知状态';
  }
};

const getStatusType = (status) => {
  switch (status) {
    case 0: return 'danger';
    case 1: return 'warning';
    case 2: return 'success';
    default: return 'info';
  }
};

const getProductShapeText = (shape = '') => {
  const found = productShapes.find(item => item.value === shape);
  return found ? found.label : shape || '未指定';
};

const getProductStructureText = (structure = '') => {
  const found = productStructures.find(item => item.value === structure);
  return found ? found.label : structure || '未指定';
};

const getClosureTypeText = (type = '') => {
  const found = closureTypes.find(item => item.value === type);
  return found ? found.label : type || '未指定';
};

const getPocketTypeText = (type = '') => {
  const found = pocketTypes.find(item => item.value === type);
  return found ? found.label : type || '未指定';
};

const getColorShadeText = (shade = '') => {
  const found = colorShades.find(item => item.value === shade);
  return found ? found.label : shade || '未指定';
};

const getPatternTypeText = (type = '') => {
  const found = patternTypes.find(item => item.value === type);
  return found ? found.label : type || '未指定';
};

const getLeatherTypeText = (type = '') => {
  const found = leatherTypes.find(item => item.value === type);
  return found ? found.label : type || '未指定';
};

const getLeatherFinishText = (finish = '') => {
  const found = leatherFinishes.find(item => item.value === finish);
  return found ? found.label : finish || '未指定';
};

const getLiningTypeText = (type = '') => {
  const found = liningTypes.find(item => item.value === type);
  return found ? found.label : type || '未指定';
};

const getSoftnessText = (softness = '') => {
  const found = softnessOptions.find(item => item.value === softness);
  return found ? found.label : softness || '未指定';
};

const getDurabilityText = (durability = '') => {
  const found = durabilityOptions.find(item => item.value === durability);
  return found ? found.label : durability || '未指定';
};

const getWaterResistanceText = (resistance = '') => {
  const found = waterResistanceOptions.find(item => item.value === resistance);
  return found ? found.label : resistance || '未指定';
};

const getShineText = (shine = '') => {
  const found = shineOptions.find(item => item.value === shine);
  return found ? found.label : shine || '未指定';
};

const getCuttingAccuracyText = (accuracy = '') => {
  const found = cuttingAccuracyOptions.find(item => item.value === accuracy);
  return found ? found.label : accuracy || '未指定';
};

const getSewingDensityText = (density = '') => {
  const found = sewingDensityOptions.find(item => item.value === density);
  return found ? found.label : density || '未指定';
};

const goBack = () => {
  router.push('/projects');
};

const enterEditMode = () => {
  isEditMode.value = true;
};

const cancelEdit = () => {
  isEditMode.value = false;
  requirements.value = JSON.parse(JSON.stringify(originalRequirements.value));
};

const saveChanges = async () => {
  let loadingInstance = null;
  try {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '保存中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    const token = localStorage.getItem('token');
    const currentReqId = parseInt(activeRequirementId.value);
    const currentReq = requirements.value.find(req => req.id === currentReqId);

    if (!currentReq) {
      throw new Error('未找到当前需求');
    }

    const response = await axios.put(`/api/requirements/${currentReqId}`, currentReq, {
      headers: { Authorization: `Bearer ${token}` }
    });

    // Handle response based on your API structure
    if (response.data && response.data.code === 200) {
      ElNotification.success({
        title: '成功',
        message: response.data.message || '需求更新成功'
      });
      // Update original requirements and exit edit mode
      originalRequirements.value = JSON.parse(JSON.stringify(requirements.value));
      isEditMode.value = false;
      // Refresh data
      await fetchRequirementDetail();
    } else {
      // Handle case where response doesn't match expected format
      const errorMsg = response.data?.message || '保存失败，未知错误';
      throw new Error(errorMsg);
    }
  } catch (error) {
    console.error('保存失败:', error);
    // Check if error message contains "成功" and handle accordingly
    if (error.message.includes('成功')) {
      ElNotification.success({
        title: '成功',
        message: error.message
      });
      originalRequirements.value = JSON.parse(JSON.stringify(requirements.value));
      isEditMode.value = false;
      await fetchRequirementDetail();
    } else {
      ElNotification.error({
        title: '错误',
        message: `保存失败: ${error.message}`
      });
    }
  } finally {
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

const printPDF = async () => {
  const loadingInstance = ElLoading.service({ lock: true, text: '准备PDF...' });

  try {
    if (!project.value || requirements.value.length === 0) {
      await Promise.all([fetchProjectInfo(), fetchRequirementDetail()]);
    }

    const printWindow = window.open('', '_blank');
    const projectInfoHTML = generateProjectInfoHTML();
    const requirementsHTML = requirements.value.map(req => generateRequirementHTML(req)).join('<div class="page-break"></div>');

    const htmlContent = `
      <!DOCTYPE html>
      <html>
        <head>
          <title>${escapeHtml(project.value.projectName)}</title>
          <style>
            body { margin: 0; padding: 5mm; font-family: "Microsoft YaHei", Arial, sans-serif; font-size: 12pt; line-height: 1.5; color: #333; }
            @page { size: A4; margin: 10mm; }
            .pdf-header { text-align: center; margin-bottom: 10mm; padding-bottom: 5mm; border-bottom: 2px solid #6a11cb; }
            .pdf-header h1 { font-size: 20pt; color: #222; margin: 0 0 3mm 0; }
            .pdf-header h2 { font-size: 16pt; color: #444; margin: 2mm 0; font-weight: normal; }
            .pdf-header h3 { font-size: 12pt; color: #666; margin: 2mm 0 0 0; }
            .section { margin-bottom: 8mm; }
            .section-title { font-size: 14pt; color: #6a11cb; margin: 5mm 0 3mm 0; padding-bottom: 2mm; border-bottom: 1px solid #eee; }
            .info-row { display: flex; flex-wrap: wrap; margin-bottom: 3mm; page-break-inside: avoid; }
            .info-item { flex: 1 0 45%; min-width: 45%; margin-right: 5%; margin-bottom: 2mm; display: flex; }
            .info-item.full-width { flex: 1 0 100%; margin-right: 0; }
            .label { font-weight: bold; min-width: 30mm; color: #555; }
            .value { flex: 1; word-break: break-word; }
            .requirement-section { margin-bottom: 10mm; page-break-after: always; }
            .requirement-section:last-child { page-break-after: auto; }
            .requirement-title { font-size: 16pt; font-weight: bold; color: #333; margin-bottom: 5mm; padding-bottom: 2mm; border-bottom: 2px solid #2575fc; }
            .page-break { page-break-after: always; visibility: hidden; height: 0; }
            .spec-table { width: 100%; border-collapse: collapse; margin: 3mm 0; }
            .spec-table th, .spec-table td { border: 1px solid #ddd; padding: 2mm; text-align: left; }
            .spec-table th { background-color: #f5f7fa; font-weight: bold; }
            @media print { body { padding: 0; } .no-print { display: none !important; } }
            .status-tag { display: inline-block; padding: 1mm 3mm; border-radius: 3px; font-size: 10pt; font-weight: bold; }
            .status-pending { background-color: #e6a23c; color: white; }
            .status-completed { background-color: #67c23a; color: white; }
            .status-cancelled { background-color: #f56c6c; color: white; }
            .color-preview { display: inline-block; width: 10mm; height: 5mm; border: 1px solid #ddd; vertical-align: middle; margin-left: 2mm; }
            .notes-content { white-space: pre-wrap; background-color: #f9f9f9; padding: 3mm; border-radius: 3px; border-left: 3px solid #6a11cb; }
          </style>
        </head>
        <body>
          ${projectInfoHTML}
          ${requirementsHTML}
        </body>
      </html>
    `;

    printWindow.document.write(htmlContent);
    printWindow.document.close();

    setTimeout(() => {
      printWindow.print();
      loadingInstance.close();
    }, 1000);
  } catch (error) {
    console.error('生成PDF失败:', error);
    ElNotification.error({ title: '错误', message: `生成PDF失败: ${error.message}` });
    loadingInstance.close();
  }
};

const generateProjectInfoHTML = () => {
  return `
    <div class="pdf-header">
      <h1>${escapeHtml(project.value.projectName)}</h1>
      <h2>项目编号: ${escapeHtml(project.value.projectCode)}</h2>
      <h3>${formatDate(project.value.createTime)}</h3>
    </div>

    <div class="section-divider"></div>

    <h3>项目基本信息</h3>
    <div class="info-row">
      <div class="info-item">
        <span class="label">项目状态：</span>
        <span class="value">${getStatusText(project.value.status)}</span>
      </div>
      <div class="info-item">
        <span class="label">创建人：</span>
        <span class="value">${store.state.user?.name || '未知'}</span>
      </div>
    </div>

    <div class="info-row">
      <div class="info-item">
        <span class="label">客户名称：</span>
        <span class="value">${escapeHtml(project.value.clientName)}</span>
      </div>
      <div class="info-item">
        <span class="label">客户联系人：</span>
        <span class="value">${escapeHtml(project.value.clientContact)}</span>
      </div>
    </div>

    <div class="info-row">
      <div class="info-item">
        <span class="label">联系电话：</span>
        <span class="value">${escapeHtml(project.value.clientPhone)}</span>
      </div>
      <div class="info-item">
        <span class="label">创建时间：</span>
        <span class="value">${formatDate(project.value.createTime)}</span>
      </div>
    </div>

    <div class="info-row">
      <div class="info-item full-width">
        <span class="label">项目目标：</span>
        <span class="value">${escapeHtml(project.value.projectGoal)}</span>
      </div>
    </div>

    <div class="section-divider"></div>

    <div class="info-row">
      <div class="info-item">
        <span class="label">需求总数：</span>
        <span class="value">${requirements.value.length}个</span>
      </div>
    </div>

    <div class="section-divider"></div>
  `;
};

const generateRequirementHTML = (req) => {
  return `
    <div class="requirement-section">
      <h2 class="requirement-title">需求 ${req.id}</h2>

      <h3 class="section-title">产品设计细节</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">文件名称：</span>
          <span class="value">${escapeHtml(req.fileName)}</span>
        </div>
        <div class="info-item">
          <span class="label">版本：</span>
          <span class="value">${escapeHtml(req.version)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">产品形状：</span>
          <span class="value">${getProductShapeText(req.productShape)}</span>
        </div>
        <div class="info-item">
          <span class="label">产品结构：</span>
          <span class="value">${getProductStructureText(req.productStructure)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">闭合类型：</span>
          <span class="value">${getClosureTypeText(req.closureType)}</span>
        </div>
        <div class="info-item">
          <span class="label">装饰：</span>
          <span class="value">${escapeHtml(req.decoration || '无')}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">口袋类型：</span>
          <span class="value">${getPocketTypeText(req.pocketType)}</span>
        </div>
        <div class="info-item">
          <span class="label">尺寸：</span>
          <span class="value">${escapeHtml(req.dimensions)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">颜色代码：</span>
          <span class="value">${escapeHtml(req.colorCode)}</span>
        </div>
        <div class="info-item">
          <span class="label">颜色色调：</span>
          <span class="value">${getColorShadeText(req.colorShade)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">图案类型：</span>
          <span class="value">${getPatternTypeText(req.patternType)}</span>
        </div>
        <div class="info-item">
          <span class="label">图案位置：</span>
          <span class="value">${escapeHtml(req.patternLocation || '无')}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">图案尺寸：</span>
          <span class="value">${escapeHtml(req.patternSize || '无')}</span>
        </div>
      </div>

      <h3 class="section-title">材质偏好</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">皮革类型：</span>
          <span class="value">${getLeatherTypeText(req.leatherType)}</span>
        </div>
        <div class="info-item">
          <span class="label">皮革厚度：</span>
          <span class="value">${escapeHtml(req.leatherThickness)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">皮革表面处理：</span>
          <span class="value">${getLeatherFinishText(req.leatherFinish)}</span>
        </div>
        <div class="info-item">
          <span class="label">内衬类型：</span>
          <span class="value">${getLiningTypeText(req.liningType)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">内衬颜色：</span>
          <span class="value">${escapeHtml(req.liningColor || '无')}</span>
        </div>
      </div>

      <h3 class="section-title">预期效果</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">柔软度：</span>
          <span class="value">${getSoftnessText(req.softness)}</span>
        </div>
        <div class="info-item">
          <span class="label">耐用性：</span>
          <span class="value">${getDurabilityText(req.durability)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item">
          <span class="label">防水性：</span>
          <span class="value">${getWaterResistanceText(req.waterResistance)}</span>
        </div>
        <div class="info-item">
          <span class="label">光泽度：</span>
          <span class="value">${getShineText(req.shine)}</span>
        </div>
      </div>

      <h3 class="section-title">工艺要求</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">切割精度：</span>
          <span class="value">${getCuttingAccuracyText(req.cuttingAccuracy)}</span>
        </div>
        <div class="info-item">
          <span class="label">缝纫密度：</span>
          <span class="value">${getSewingDensityText(req.sewingDensity)}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item full-width">
          <span class="label">组装顺序：</span>
          <span class="value">${escapeHtml(req.assemblyOrder || '无特殊要求')}</span>
        </div>
      </div>

      <h3 class="section-title">成本要求</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">材料成本：</span>
          <span class="value">${escapeHtml(req.materialCost || '未指定')}</span>
        </div>
        <div class="info-item">
          <span class="label">加工成本：</span>
          <span class="value">${escapeHtml(req.processingCost || '未指定')}</span>
        </div>
      </div>

      <h3 class="section-title">生产可行性</h3>
      <div class="info-row">
        <div class="info-item">
          <span class="label">工艺可行性：</span>
          <span class="value">${escapeHtml(req.processFeasibility || '未评估')}</span>
        </div>
        <div class="info-item">
          <span class="label">生产周期：</span>
          <span class="value">${escapeHtml(req.productionTime || '未评估')}</span>
        </div>
      </div>

      <div class="info-row">
        <div class="info-item full-width">
          <span class="label">备注：</span>
          <span class="value">${escapeHtml(req.notes || '无')}</span>
        </div>
      </div>
    </div>
  `;
};

onMounted(async () => {
  if (!store.state.user) {
    try {
      await store.dispatch('fetchUserInfo');
    } catch (error) {
      console.error('获取用户信息失败:', error);
      ElNotification.error({ title: '错误', message: '获取用户信息失败，请重新登录' });
    }
  }

  await fetchProjectInfo();
  await fetchRequirementDetail();
});
</script>

<style scoped>
.project-detail-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.top-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  transition: all 0.3s ease;
}

.top-left {
  display: flex;
  align-items: center;
  min-width: 300px;
}

.logo {
  height: 36px;
  margin-right: 12px;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: scale(1.05);
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.detail-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bolder;
  color: black;
  padding: 0 20px;
}

.buttons {
  display: flex;
  gap: 10px;
  min-width: 120px;
}

.primary-button {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.primary-button:hover {
  background: linear-gradient(45deg, #5a01bb, #1565ec);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.primary-button i {
  margin-right: 6px;
  font-size: 14px;
}

.download-button {
  background: linear-gradient(45deg, #2196f3, #21cbf3);
  color: white;
}

.download-button:hover {
  background: linear-gradient(45deg, #1976d2, #0bb8e3);
}

.edit-button {
  background: linear-gradient(45deg, #4caf50, #8bc34a);
  color: white;
}

.edit-button:hover {
  background: linear-gradient(45deg, #388e3c, #7cb342);
}

.main-content {
  padding: 20px;
  flex-grow: 1;
}

.project-info-card,
.requirement-detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.project-info-card:hover,
.requirement-detail-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(to right, #f8f9fa, #ffffff);
  border-bottom: 1px solid #eaeaea;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
  position: relative;
  padding-left: 12px;
}

.card-header h2:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background: linear-gradient(to bottom, #6a11cb, #2575fc);
  border-radius: 2px;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.info-item {
  flex: 1;
  display: flex;
  min-width: 250px;
  padding: 4px 0;
}

.info-item.full-width {
  flex: 2;
  min-width: 100%;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
  min-width: 100px;
}

.value {
  color: #303133;
  word-break: break-word;
}

.loading-container {
  padding: 20px;
}

.error-message {
  padding: 20px;
  text-align: center;
}

.requirement-tabs {
  padding: 10px;
}

.requirement-tabs :deep(.el-tabs__nav) {
  border-radius: 4px;
  overflow: hidden;
}

.requirement-tabs :deep(.el-tabs__item) {
  transition: all 0.3s ease;
  height: 40px;
  line-height: 40px;
}

.requirement-tabs :deep(.el-tabs__item.is-active) {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #6a11cb;
}

.requirement-tabs :deep(.el-tabs__active-bar) {
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  height: 3px;
}

.tab-content {
  padding: 15px 10px;
  background-color: #fff;
  border-radius: 0 0 8px 8px;
}

/* PDF模板样式 */
.pdf-template {
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  width: 210mm;
  min-height: 297mm;
  padding: 20mm;
  box-sizing: border-box;
  background-color: white;
  color: #333;
  line-height: 1.5;
}

.pdf-header {
  text-align: center;
  margin-bottom: 15mm;
  border-bottom: 1px solid #eee;
  padding-bottom: 10mm;
}

.pdf-header h1 {
  font-size: 16pt;
  margin-bottom: 5mm;
}

.pdf-header h2 {
  font-size: 14pt;
  color: #666;
}

.pdf-content h3 {
  font-size: 12pt;
  margin: 8mm 0 5mm 0;
  padding-bottom: 2mm;
  border-bottom: 1px solid #eee;
  color: #444;
}

.pdf-content .info-row {
  display: flex;
  margin-bottom: 3mm;
}

.pdf-content .info-item {
  flex: 1;
  display: flex;
}

.pdf-content .info-item.full-width {
  flex: 2;
}

.pdf-content .label {
  font-weight: bold;
  min-width: 30mm;
  color: #555;
}

.pdf-content .value {
  flex: 1;
  word-break: break-all;
}
</style>